package com.wrupple.muba.common.client.activity;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.domain.DesktopPlace;

public class ApplicationActivityFactory implements DesktopActivity {

	protected MubaWebappLoader loader;
	private Activity current;
	private boolean cancelled;

	public ApplicationActivityFactory(MubaWebappLoader loader) {
		super();
		this.loader = loader;
	}

	@Override
	public void start(final AcceptsOneWidget panel, final EventBus eventBus) {
		this.cancelled=false;
		loader.loadActivity(this, new DataCallback<Activity>() {

			@Override
			public void execute() {
				current = result;
				if(!cancelled){
					result.start(panel, eventBus);
				}
			}

		});
	}

	@Override
	public void getActivityProcess(final DesktopPlace item, final DataCallback<ActivityProcess> callback) {
		loadActivity(this, new DataCallback<Activity>() {
			@Override
			public void execute() {
				current = result;
				if (result instanceof DesktopActivity) {
					((DesktopActivity) result).getActivityProcess(item, callback);
				} else {
					throw new IllegalArgumentException("Activity is not sequential");
				}
			}
		});
	}

	private void loadActivity(
			ApplicationActivityFactory applicationActivityFactory,
			DataCallback<Activity> dataCallback) {
		
		
	}

	@Override
	public String mayStop() {
		if (current == null) {
			return null;
		}else{
			return current.mayStop();
		}
		
	}

	@Override
	public void onCancel() {
		if (current == null) {
			this.cancelled=true;
		}else{
			current.onCancel();
		}
	}

	@Override
	public void onStop() {
		if (current == null) {
			this.cancelled=true;
		}else{
			current.onStop();
		}
	}


}